package cn.znzz.cjm.order.service.impl;


import cn.znzz.cjm.basic.service.impl.BaseServiceImpl;
import cn.znzz.cjm.basic.util.CodeGenerateUtils;
import cn.znzz.cjm.basic.util.PageList;
import cn.znzz.cjm.order.domain.OrderAddress;
import cn.znzz.cjm.order.domain.ProductOrder;
import cn.znzz.cjm.order.mapper.OrderAddressMapper;
import cn.znzz.cjm.order.mapper.ProductOrderMapper;
import cn.znzz.cjm.order.query.ProductOrderQuery;
import cn.znzz.cjm.order.service.IProductOrderService;
import cn.znzz.cjm.org.domain.Employee;
import cn.znzz.cjm.org.mapper.EmployeeMapper;
import cn.znzz.cjm.pay.constants.PayConstants;
import cn.znzz.cjm.pay.domain.PayBill;
import cn.znzz.cjm.pay.mapper.PayBillMapper;
import cn.znzz.cjm.pay.service.IPayBillService;
import cn.znzz.cjm.product.domain.Product;
import cn.znzz.cjm.product.mapper.ProductMapper;
import cn.znzz.cjm.quartz.constant.JobTypeConstants;
import cn.znzz.cjm.quartz.service.IQuartzService;
import cn.znzz.cjm.quartz.util.QuartzJobInfo;
import cn.znzz.cjm.user.domain.Logininfo;
import cn.znzz.cjm.user.domain.User;
import cn.znzz.cjm.user.domain.UserAddress;
import cn.znzz.cjm.user.mapper.UserAddressMapper;
import cn.znzz.cjm.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;

    @Value("${order.last.pay.time}")
    private Integer lastPayTime;

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;

    //宠物订单
    @Override
    public String submit(Map<String, Object> params, Logininfo currentLogin) {
        Integer servicMethod =Integer.valueOf(params.get("service_method").toString());
        Long addressId =Long.valueOf(params.get("address_id").toString());
        Long payMethod =Long.valueOf(params.get("pay_method").toString());
        Long productId =Long.valueOf(params.get("product_id").toString());
        Long productNum =Long.valueOf(params.get("product_num").toString());
        //1.库存-productNum
        Product product = productMapper.loadById(productId);
        product.setSalecount(product.getSalecount()-productNum);
        //2.生狗领养订单
        User user = userMapper.loadByLogininfoId(currentLogin.getId());

        ProductOrder order = initProductOrder(product, user);
        //提前生成统一支付账号
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        productOrderMapper.save(order);//拿到自增的id
        //.谁领养的
        //.收购人地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);

        orderAddressMapper.save(orderAddress);
        //3.保存订单
        System.out.println("支付成功，宁的支付金额为："+order.getPrice());
        //支付订单
        PayBill bill = initPayBill(payMethod, product, user, order);
        //保存数据
        payBillMapper.save(bill);//返回自增ID
        //生成订单

        //超时未支付取消
        QuartzJobInfo jobInfo = new QuartzJobInfo();

        String jobName= JobTypeConstants.TIME_OUT_PRODUCTS_LAST_PAY+order.getId();
        jobInfo.setJobName(jobName);
        Map<String, Object> map = new HashMap<>();
        map.put("type",JobTypeConstants.TIME_OUT_PRODUCTS_LAST_PAY);
        map.put("orderId",order.getId());
        jobInfo.setParams(map);
        jobInfo.setFireDate(order.getLastPayTime());
        quartzService.addJob(jobInfo);

        return payBillService.pay(bill);

    }

    private PayBill initPayBill(Long payMethod, Product product, User user, ProductOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]对"+product.getName()+"支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayConstants.BUSINESS_TYPE_PRODUCT);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    @Override
    public PageList<ProductOrder> queryUserOrder(ProductOrderQuery query, Logininfo currentLogin) {
        User user = userMapper.loadByLogininfoId(currentLogin.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<ProductOrder> queryAdmin(ProductOrderQuery query, Logininfo currentLogin) {
        Employee employee = employeeMapper.loadByLoginInfoId(currentLogin.getId());
        if(employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public ProductOrder queryById(Long id) {
        return productOrderMapper.loadById(id);
    }

    @Override
    public void cancelByQuartz(Long orderId) {
        ProductOrder productOrder = productOrderMapper.loadById(orderId);
        if(productOrder!=null){
            //必须要是待支付，才修改为取消
            if(productOrder.getState() == -1){
                //需要主动查询支付宝是否完成支付，没有支付才执行，懒得做
                productOrder.setState(-1);
                productOrderMapper.update(productOrder);
            }
        }
    }

    private OrderAddress initOrderAddress(ProductOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private ProductOrder initProductOrder(Product product, User user) {
        ProductOrder order = new ProductOrder();
        order.setDigest("[摘要]对"+product.getName()+"收购订单！");
        order.setState(0);//待支付
        order.setPrice(product.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);//订单编号
        order.setProduct_id(product.getId());
        order.setUser_id(user.getId());
        order.setShop_id(product.getShop_id());
        order.setLastPayTime(new Date(System.currentTimeMillis() + lastPayTime));
        return order;
    }
}
